#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : synthesis_audio_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/27 10:42
"""
import json
import traceback
import tempfile
from PyQt5.QtCore import QThread, pyqtSignal
from utils.tools import request
from config import Config


class SynthesisAudioWorker(QThread):
    """合成音频线程"""
    result = pyqtSignal(str)
    failed = pyqtSignal(Exception)

    def __init__(self, content, headers, parent=None):
        super(SynthesisAudioWorker, self).__init__()
        self.headers = headers
        self.content = json.loads(content)

    def run(self):
        try:
            payload = json.dumps({
                    "text": self.content["text"],
                    "model": self.content["model"],
                    "voice": self.content["voice"],
                    "suffix": "mp3",
                    "volume": self.content["volume"],
                    "rate": self.content["speed"],
                    "pitch": self.content["pitch"],

            })
            url = f"{Config.Host}/api/synthesis/audio/"
            self.headers.update({'Content-Type': 'application/json'})
            response = request(url, method='POST', headers=self.headers, data=payload)
            response.raise_for_status()
            file_url = response.json()["file_url"]
            audio_content = request(file_url).content
            temp_file = tempfile.mktemp(suffix=".mp3", dir=self.content["output_dir"])
            with open(temp_file, "wb") as f:
                f.write(audio_content)
            # TODO: 这里应该是发送信号给主线程，告诉主线程音频素材已经加载完成
            # TODO: 打开文件夹

        except Exception as e:
            traceback.print_exc()
            self.failed.emit(e)